package com.biodiv.client.auto;

import com.biodiv.client.PBankClient;
import com.biodiv.miracle.support.annotation.ConditionalOnMissingBean;
import com.biodiv.miracle.support.annotation.Configuration;
import com.biodiv.miracle.support.utils.ResourceUtils;

import java.util.Properties;

/**
 * @author: tianquan
 * @date: 2025-05-31  15:33
 * @description: 注册中心客户端自动装配类
 */
@Configuration
public class PBankClientAutoConfiguration {

    private String serviceName;

    private String userName;

    private String password;

    private String address;

    private Integer serverPort;

    private Integer servicePort;

    public PBankClientAutoConfiguration() {
        // 解析配置文件
        Properties properties = ResourceUtils.getProperties();
        // 注册中心服务端 端口
        String serverPort = properties.getProperty("miracle.PBank.server.port");
        if (serverPort != null) {
            this.serverPort = Integer.parseInt(serverPort);
        } else {
            this.serverPort = 9850;
        }

        // 注册中心服务端 端口
        String servicePort = properties.getProperty("server.port");
        if (servicePort != null) {
            this.servicePort = Integer.parseInt(servicePort);
        } else {
            this.servicePort = 8080;
        }

        this.serviceName = properties.getProperty("miracle.PBank.client.service.name");
        this.userName = properties.getProperty("miracle.PBank.user.name");
        this.password = properties.getProperty("miracle.PBank.user.password");
        this.address = properties.getProperty("miracle.PBank.server.address");

    }

    @ConditionalOnMissingBean
    public PBankClient pbankClient() {
        // 一个参数都不能为空
        if (serviceName == null || userName == null || password == null || address == null) {
            return null;
        }
        PBankClient pBankClient = PBankClient.PBankClientBuilder.builder()
                .user(userName)
                .password(password)
                .address(address)
                .port(serverPort)
                .serverName(serviceName)
                .servicePort(servicePort)
                .build();
        //  启动客户端
        new Thread(pBankClient::startClient).start();
        return pBankClient;
    }

}
